package com.zefor.form;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.cache.AppCache;
import kd.bos.entity.cache.IAppCache;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IPageCache;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.mvc.form.FormDataModel;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EventObject;
import java.util.logging.SimpleFormatter;

public class ElectricityRecordingForm extends AbstractFormPlugin {

    private final ORM orm = ORM.create();

    @Override
    public void afterCreateNewData(EventObject e) {
        //获取父表单传入的参数
        IPageCache pageCache = this.getPageCache();
        String breedingFarmId = pageCache.get("breedingFarmId");
        if (breedingFarmId != null){
            // System.out.println("养殖场id："+breedingFarmId);
            QFilter qFilter = new QFilter("id",QCP.equals,Long.parseLong(breedingFarmId));
            DynamicObject dynamicObject = orm.queryOne("n716_farm", "*", qFilter.toArray());
            qFilter = new QFilter("n716_basedatafield",QCP.equals,Long.parseLong(breedingFarmId));
            DynamicObjectCollection dynamicObjects = orm.query("n716_ele_info", "*", qFilter.toArray());
            double ymds = 0,tmds = 0,tms = 0;
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String date = format.format(new Date());
            for (DynamicObject d : dynamicObjects){
                if (format.format(d.get(8)).equals(date)){
                    ymds += Double.parseDouble(d.get(10).toString()==null?"0":d.get(10).toString());
                    tmds += Double.parseDouble(d.get(11).toString()==null?"0":d.get(11).toString());
                    tms += Double.parseDouble(d.get(12).toString()==null?"0":d.get(12).toString());
                }
            }
            this.getModel().setValue("n716_ymds", String.valueOf(ymds));
            this.getModel().setValue("n716_tmds", String.valueOf(tmds));
            this.getModel().setValue("n716_tms", String.valueOf(tms)    );
            this.getModel().setValue("n716_basedatafield",dynamicObject);
        }
    }


    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("tblnew");

    }

    @Override
    public void addClickListeners(String... keys) {
        //点击确定按钮
        if (keys != null){
            if (keys[0].equals("tblnew")){
                DynamicObject breedingFarmObj = (DynamicObject) this.getModel().getValue("n716_basedatafield");
                IPageCache pageCache = this.getPageCache();
                pageCache.put("breedingFarmId",breedingFarmObj.get(0).toString());
            }
        }

    }
}
